package com.linq.cool.gateway.service.impl;

import com.linq.cool.common.constants.Constants;
import com.linq.cool.common.core.domain.Result;
import com.linq.cool.common.core.exception.ValidateCodeException;
import com.linq.cool.common.core.utils.IdUtils;
import com.linq.cool.common.core.utils.StringUtils;
import com.linq.cool.common.redis.service.RedisService;
import com.linq.cool.gateway.config.captcha.CaptchaProperties;
import com.linq.cool.gateway.service.ValidateCodeService;
import com.wf.captcha.base.Captcha;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author: yqlin
 * @Date: 2021/1/21 04:03
 * @Description: 验证码实现处理
 * @Version: 1.0.0
 */
@Slf4j
@Service
public class ValidateCodeServiceImpl implements ValidateCodeService {
    @Autowired
    private CaptchaProperties captchaProperties;

    @Autowired
    private RedisService redisService;

    @Override
    public Result<?> createCaptcha() throws IOException, ValidateCodeException {
        // 获取运算的结果
        Captcha captcha = captchaProperties.getCaptcha();
        // 唯一标识
        String uuid = IdUtils.simpleUUID();
        log.info("获取的code为: {} , uuid为: {}", captcha.text(), uuid);
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
        // 保存到redis
        redisService.setCacheObject(verifyKey, captcha.text(), captchaProperties.getCaptchaCode().getExpiration(), TimeUnit.MINUTES);
        Map<String, Object> map = new HashMap<>(2);
        map.put("uuid", uuid);
        map.put("img", captcha.toBase64());
        return Result.ok(map);
    }

    @Override
    public void checkCaptcha(String code, String uuid) throws ValidateCodeException {
        if (StringUtils.isBlank(code)) {
            throw new ValidateCodeException("验证码不能为空");
        }
        if (StringUtils.isBlank(uuid)) {
            throw new ValidateCodeException("验证码已失效");
        }
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
        String captcha = redisService.getCacheObject(verifyKey);
        redisService.deleteObject(verifyKey);
        if (!code.equalsIgnoreCase(captcha)) {
            throw new ValidateCodeException("验证码错误");
        }
    }
}
